//
//  LocationViewController.m
//  TQY
//
//  Created by 甘世清 on 2024/11/1.
//

#import "LocationViewController.h"

@interface LocationViewController ()<MKMapViewDelegate,UITextFieldDelegate>
@property (nonatomic , strong) MKMapView * mapView;
@property (nonatomic , strong) HeaderView * addButton;
@property (nonatomic , strong) UILabel * addressLabel;
@property (nonatomic , strong) CLPlacemark * seletedPlace;

@end

@implementation LocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (void)SQ_UIViewForSelfView{
    [self.view addSubview:self.mapView];
    
    SQCustomButton * add = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(30, 30) midmargin:0];
    add.image = SQGetImage(@"IM取消");
    [self.view addSubview:add];
    [add mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(TopHeight-50);
        make.size.mas_equalTo(50);
        make.right.equalTo(self.view.mas_right).offset(-4);
    }];
    WS(weakSelf);
    [add setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    UIImageView * image = [[UIImageView alloc]init];
    image.image = SQGetImage(@"located_pin");
    image.contentMode = UIViewContentModeScaleAspectFit;
    [self.mapView addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mapView);
        make.centerY.equalTo(self.mapView).offset(-10);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(40);
    }];
    [self.view addSubview:self.addressLabel];
    [self.addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(image.mas_top).offset(-4);
        make.width.mas_equalTo(SCREEN_WIDETH/2.f);
    }];
    [self.view addSubview:self.addButton];
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(SCREEN_WIDETH-60);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-20);
        make.height.mas_equalTo(50);
    }];
    [self SQ_setMap];
}
-(void)SQ_setMap{
    CLLocationCoordinate2D coordinate2D = CLLocationCoordinate2DMake(self.mapView.userLocation.location.coordinate.latitude, self.mapView.userLocation.location.coordinate.longitude);
       // 设置地图显示区域的缩放级别
       float zoomLevel = 10;
       // 初始化一个常量，表示地图对象的显示区域
       MKCoordinateRegion region = MKCoordinateRegionMake(coordinate2D, MKCoordinateSpanMake(zoomLevel, zoomLevel));
       // 设置地图对象的显示区域
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}
//位置已经改变了
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
  
    CLLocationCoordinate2D  location =  [self.mapView convertPoint:CGPointMake(SCREEN_WIDETH/2.f, self.mapView.frame.size.height/2.f) toCoordinateFromView:self.mapView];
         CLGeocoder *gecoder = [[CLGeocoder alloc]init];
         CLLocation *locations = [[CLLocation alloc]initWithLatitude:location.latitude longitude:location.longitude];
    WS(weakSelf);
        [gecoder reverseGeocodeLocation:locations completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            
            if (placemarks.count > 0) {
                CLPlacemark * place = placemarks.firstObject;
                self.seletedPlace = place;
                NSString *city = place.locality;
                if ([city isNotEmpty]) {
                    weakSelf.addressLabel.text = [NSString stringWithFormat:@"%@%@",place.locality,place.thoroughfare];
                   
                } else {
                    weakSelf.addressLabel.text = [NSString stringWithFormat:@"%@%@",place.administrativeArea,place.thoroughfare];
                }
                weakSelf.addressLabel.text = [weakSelf.addressLabel.text stringByReplacingOccurrencesOfString:@"null" withString:@""];
                weakSelf.addressLabel.text = [weakSelf.addressLabel.text stringByReplacingOccurrencesOfString:@"()" withString:@""];
            }
        }];
}

-(UIImage*)SQ_imageatFrame:(CGRect)rect{
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_WIDETH, SCREEN_HEIGHT), NO, 0.0f);
    [self.mapView drawViewHierarchyInRect:CGRectMake(0,0, self.mapView.bounds.size.width, self.mapView.bounds.size.height) afterScreenUpdates:YES];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}
-(void)SQ_addAnntionForMap{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    [HttpTool SQ_Image:[self SQ_imageatFrame:CGRectMake(0, (SCREEN_HEIGHT-(SCREEN_WIDETH*0.618))/2.f, SCREEN_WIDETH, SCREEN_WIDETH*0.618)] successBlock:^(BaseModel * _Nonnull httpModel) {
        NSString * addressImage = [NSString stringWithFormat:@"%@",httpModel.data];
        [self SQ_sendLocation:addressImage];
            
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}
-(void)SQ_sendLocation:(NSString*)locationUrl{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:locationUrl forKey:@"content"];
    [dic setObject:@(self.seletedPlace.location.coordinate.latitude) forKey:@"lat"];
    [dic setObject:@(self.seletedPlace.location.coordinate.longitude) forKey:@"lng"];
    [dic setObject:self.addressLabel.text forKey:@"address"];
    if (self.addressBlock) {
        self.addressBlock(dic);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc {
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode  = MKUserTrackingModeNone;
    [_mapView.layer removeAllAnimations];
    [_mapView removeAnnotations:_mapView.annotations];
    [_mapView removeOverlays:_mapView.overlays];
    [_mapView removeFromSuperview];
    _mapView.delegate = nil;
    _mapView = nil;
}
- (HeaderView *)addButton{
    if (!_addButton) {
        _addButton = [[HeaderView alloc]init];
        _addButton.colorString = @"#FFFFFF";
        _addButton.backgroundColor = SQColor3DA59D;
        _addButton.layer.cornerRadius = 25;
        _addButton.layer.masksToBounds = YES;
        _addButton.btn.mm_acceptEventInterval = 3;
        [_addButton.btn addTarget:self action:@selector(SQ_addAnntionForMap) forControlEvents:UIControlEventTouchUpInside];
        _addButton.layer.cornerRadius = 6;
        _addButton.layer.masksToBounds = YES;
        _addButton.text = SQNSLocalString(@"发送");
        _addButton.font = FONT_MEDIUM(18);
    }
    return _addButton;
}

- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
        /** 设置地图类型 */
        _mapView.mapType = MKMapTypeStandard;
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        //设置地图可缩放
        _mapView.zoomEnabled = YES;
        //设置地图可滚动
        _mapView.scrollEnabled = YES;
        //设置地图可旋转
        _mapView.rotateEnabled = YES;
        //设置显示用户显示位置
        _mapView.showsUserLocation = YES;
        //为MKMapView设置delegate
        _mapView.delegate = self;
        _mapView.showsBuildings = YES;
        _mapView.showsTraffic = YES;
    }
    return _mapView;
}

- (UILabel *)addressLabel{
    if (!_addressLabel) {
        _addressLabel = [[UILabel alloc]init];
//        _addressLabel.backgroundColor = SQHexColor(@"#000000", 0.3);
        _addressLabel.font = FONT_REGULAR(12);
        _addressLabel.textColor = UIColor.whiteColor;
        _addressLabel.numberOfLines = 0;
        _addressLabel.textAlignment = NSTextAlignmentCenter;
//        _addressLabel.layer.cornerRadius = 2;
    }
    return _addressLabel;
}
@end
